package com.whz.governance.redislimiter.tool;

import lombok.experimental.UtilityClass;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

/**
 * @author whz
 */
@UtilityClass
class InstantUtils {

    /**
     * Gets the number of the unit from the Java epoch of 1970-01-01T00:00:00Z
     *
     * @param unit time unit ,must greater than MICROS and NANOS
     * @return the number of the unit from the Java epoch of 1970-01-01T00:00:00Z
     */
    public long currentUnitDuration(ChronoUnit unit) {
        if (unit == ChronoUnit.MICROS || unit == ChronoUnit.NANOS || unit == ChronoUnit.MILLIS) {
            return System.currentTimeMillis();
        }
        return System.currentTimeMillis() / unit.getDuration().toMillis();
    }

    public long currentSeconds() {
        return Instant.now().getEpochSecond();
    }

    public long getTtl(int replenishRate, int burstCapacity, ChronoUnit unit) {
        switch (unit) {
        case NANOS:
        case MICROS:
        case MILLIS:
            throw new RuntimeException("min time unit is second. Not Support Unit:" + unit);
        default:
            return BigDecimal.valueOf(unit.getDuration().getSeconds()).multiply(getRate(replenishRate, burstCapacity))
                             .longValue();
        }
    }

    private BigDecimal getRate(int replenishRate, int burstCapacity) {
        return BigDecimal.valueOf(burstCapacity).divide(BigDecimal.valueOf(replenishRate), 2, RoundingMode.HALF_DOWN);
    }
}